import React, { useState, useImperativeHandle, useEffect } from 'react';
import { Row, Col, InputNumber, Input, Switch, Message, Form, message, Select } from 'antd';
import FormItem from 'src/components/FormItem';
import useTagData from 'src/hook/useTagData';
import { compare } from 'src/utils/compare';
import ActionConfig from '../ActionConfig';
import Conditions from './conditions';
import HitHandleBySelectLogic from '../HitHandleBySelectLogic';
import { STRATEGY_MODE } from 'src/utils/constant';
import { cloneDeep } from 'lodash';
import { validateRuleItem } from 'src/utils/json';
import './index.less';
import { connect } from 'react-redux';
import useRiskTypes from '../../../../../hook/useRiskTypes';

function RuleConfig(props) {
  const { otherRules } = props;
  const [value, setValue] = useState(props.value || {});
  console.log(props);
  const tagList = useTagData();
  const riskTypes = useRiskTypes();
  const riskLevels = props.codes.risk_level
    ? props.codes.risk_level.map((it) => {
        return { code: it.key, name: it.value };
      })
    : [];

  useEffect(() => {
    props.value && setValue(props.value);
  }, [props.value]);

  useImperativeHandle(props.ruleRef, () => ({
    // 暴露方法给父组件,收集验证值
    getValue: (cb) => {
      props.form.validateFields((err, values) => {
        if (!err) {
          const { tags } = values;
          values.tags =
            tags &&
            tags.map((item) => {
              const tempObj = tagList.find((el) => el.code === item);
              if (tempObj) {
                const { code, name } = tempObj;
                return { code, name };
              }
            });
          // const reg2 = /([|]{2}|[&]{2}|[()])/g;
          // const newExpress = values.condition_express.replace(reg2, '-');
          // const arr = newExpress.split('-');
          // let isexit = false;
          // arr.forEach((item) => {
          //   if (item && Number(item) > value.conditions.length) {
          //     return (isexit = item);
          //   }
          // });
          // if (isexit) return message.warn(`条件表达式序号${isexit}不存在`);
          const isValidate = validate(value); // 验证数据
          if (isValidate) {
            cb({ ...value, ...values }, null);
          } else {
            cb({ ...value, ...values }, true);
          }
        }
      });
      // const isValidate = validate(value); // 验证数据
      // if (isValidate) {
      //   cb(value, null);
      // } else {
      //   cb(value, true);
      // }
    },
  }));

  // 验证数据
  function validate(value) {
    try {
      validateRuleItem(value);
      return true;
    } catch (error) {
      Message.warning(error);
      return false;
    }
  }

  function validatorName(rule, value, callback) {
    const isSameOne = otherRules.find((it) => it.name === value);
    if (isSameOne) {
      callback(`规则名称已存在`);
    } else {
      callback();
    }
  }
  function validatorCode(rule, value, callback) {
    const isSameOne = otherRules.find((it) => it.code === value);
    if (isSameOne) {
      callback(`规则CODE已存在`);
    } else {
      callback();
    }
  }

  // function formatter(value) {
  //   if (typeof value === 'string') {
  //     return !isNaN(Number(value)) ? value.replace(/[^\d]/g, '') : '';
  //   } else if (typeof value === 'number') {
  //     return !isNaN(value) ? String(value).replace(/[^\d]/g, '') : '';
  //   } else {
  //     return '';
  //   }
  // }

  const layout = {
    labelCol: {
      span: 8,
    },
    wrapperCol: {
      span: 16,
    },
  };
  const formItems = [
    {
      label: {
        label: '规则名称',
        ...layout,
      },
      name: `name`,
      options: {
        initialValue: value.name,
        rules: [
          { required: true, message: '请输入' },
          { pattern: /^[\u4E00-\u9FA5_a-zA-Z0-9]+$/, message: '限中英文数字下划线' },
          { max: 128, message: '最长128个字符' },
          {
            validator: validatorName,
          },
        ],
      },
      component: <Input placeholder='请输入' disabled={props.disabled} style={compare(props)} />,
    },
    {
      label: {
        label: '规则CODE',
        ...layout,
      },
      name: `code`,
      options: {
        initialValue: value.code,
        rules: [
          { required: true, message: '请输入规则CODE' },
          { max: 128, message: '最长128个字符' },
          { pattern: /^[a-zA-Z][_a-zA-Z0-9]*$/, message: '限英文数字下划线，并以英文开头' },
          {
            validator: validatorCode,
          },
        ],
      },
      component: <Input placeholder='请输入' disabled={props.disabled} style={compare(props)} />,
    },
    {
      label: {
        label: '执行优先级',
        ...layout,
      },
      name: `priority`,
      options: {
        initialValue: value.priority,
        rules: [{ required: true, message: '请输入' }],
      },
      component: (
        <InputNumber
          step={1}
          min={0}
          max={9999}
          placeholder='请输入'
          disabled={props.disabled}
          style={compare(props)}
          precision={0}
          // parser={formatter}
        />
      ),
    },
    {
      label: {
        label: '是否启用',
        ...layout,
      },
      name: `enabled`,
      options: {
        initialValue: value.enabled,
        valuePropName: 'checked',
      },
      component: <Switch />,
    },
    {
      label: {
        label: '规则标签',
        ...layout,
      },
      name: 'tags',
      options: {
        initialValue: value.tags && value.tags.map((item) => item.code),
        // rules: [{ required: true, message: '请选择' }],
      },
      component: (
        <Select placeholder='请选择' mode='multiple' disabled={props.disabled} style={compare(props)}>
          {tagList.map((item) => (
            <Select.Option key={item.id} value={item.code} disabled={props.disabled}>
              {item.name}
            </Select.Option>
          ))}
        </Select>
      ),
    },
  ];

  function changeHandle(val) {
    setValue(cloneDeep({ ...value, ...val }));
  }

  function handleSubmit(e, type) {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      console.log(err);
      if (!err) {
      }
    });
  }

  return (
    <Form onSubmit={handleSubmit} className='stretegy-content'>
      <div className='tantuer-field-area' style={{ padding: '30px 0 0 0' }}>
        <Row type='flex' justify='start' gutter={10} align='middle'>
          {formItems.map((item) => {
            return (
              <Col span={8} key={item.name}>
                <FormItem form={props.form} item={item} colNum={1} />
              </Col>
            );
          })}
        </Row>
        <div className='tantuer-field-area' style={{ padding: '30px 0 0 0' }}>
          <div className='form-title'>条件配置</div>
          {/* <HitHandleByExpression form={props.form} value={value.condition_express} /> */}
          <HitHandleBySelectLogic
            value={value.condition.junction_type}
            onChange={(val) => changeHandle({ condition: { ...value.condition, junction_type: val } })}
          />
          <Conditions
            {...props}
            variable={props.variable}
            value={value.condition.conditions}
            operatorOptions={props.operator}
            onChange={(val) => changeHandle({ condition: { ...value.condition, conditions: val } })}
          />
        </div>
        <div className='tantuer-field-area' style={{ padding: '30px 0 0 0' }}>
          <div className='form-title'>动作配置</div>
          <ActionConfig
            {...props}
            disabled={props.disabled}
            variable={props.variable}
            using_variables={props.using_variables}
            actions={props.actions}
            value={value.condition_actions}
            compareData={
              (props.compareData &&
                props.compareData.strategy_config &&
                props.compareData.strategy_config.mode &&
                props.compareData.strategy_config.mode.express_rules &&
                props.compareData.strategy_config.mode.express_rules[0] &&
                props.compareData.strategy_config.mode.express_rules[0].condition_actions) ||
              {}
            }
            type={STRATEGY_MODE._RULESET}
            onChange={(value) => changeHandle({ condition_actions: value })}
            isInitOne={true}
            allowEmpyt={true} // 允许为空
            riskTypes={riskTypes}
            riskLevels={riskLevels}
          />
        </div>
      </div>
    </Form>
  );
}

function mapStateToProps(state) {
  return {
    codes: {
      ...state.code,
    },
  };
}
export default connect(mapStateToProps)(Form.create()(RuleConfig));
